package com.crm.system.service.impl.customerManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.EasyExcelUtil;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerPay;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.customerManager.CustomerPayQO;
import com.crm.model.vo.customerManager.CustomerPayDetailVO;
import com.crm.model.vo.customerManager.CustomerPayExport;
import com.crm.model.vo.customerManager.CustomerPayVO;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPayDbService;
import com.crm.system.service.customerManager.CustomerPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author:chaifuyou
 * @Date: 2021/4/30 9:47
 */
@Service
public class CustomerPayServiceImpl implements CustomerPayService {
    
    @Autowired
    private CustomerPayDbService customerPayDbService;

    @Autowired
    private CustomerDbService customerDbService;

    /**
     * 客户充值列表
     * @param pageIndex
     * @param pageSize
     * @param sortName
     * @param sortOrder
     * @param qo
     * @return
     */
    @Override
    public DhPageInfo<CustomerPayVO> selectCustomerPayList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, CustomerPayQO qo) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        String deptId = userAccount.getDeptId();
        if ("4".equals(deptId)){
            qo.setCompanyId(userAccount.getCompanyId());
        }
        if (!"3".equals(deptId) && !"4".equals(deptId)){
            qo.setAccountId(userAccount.getAccountId());
        }
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("t.create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "customerName":
                {
                    order.append("c.customer_name ").append(sortOrder);//客户名称
                }
                break;
                case "payMoney":
                {
                    order.append("t.pay_money ").append(sortOrder);//金额
                }
                break;
                case "payType":
                {
                    order.append("t.pay_type ").append(sortOrder);//充值类型
                }
                break;
                case "payStatus":
                {
                    order.append("t.pay_status ").append(sortOrder);//充值状态
                }
                break;
                case "createPeopleName":
                {
                    order.append("u.user_name ").append(sortOrder);//申请人
                }
                break;
                case "companyName":
                {
                    order.append("com.company_name ").append(sortOrder);//公司名称
                }
                break;
                case "financeName":
                {
                    order.append("fu.user_name ").append(sortOrder);//审批人
                }
                break;
                case "paymentDate":
                {
                    order.append("t.payment_date ").append(sortOrder);//审批人
                }
                break;
                default:
                    break;
            }
        }
        Integer dateUnit=getDateUnit(qo.getDateType());
        List<CustomerPayVO> resultList = customerPayDbService.selectCustomerPayList(dateUnit,order,qo);
        PageInfo<CustomerPayVO> pageInfo = new PageInfo<CustomerPayVO>(resultList);
        return new DhPageInfo<CustomerPayVO>(pageInfo, resultList);
    }

    @Override
    public boolean exportCustomerPayList(CustomerPayQO customerPayQO, ServletOutputStream outputStream) {
        DhPageInfo<CustomerPayVO> customerPayVODhPageInfo = selectCustomerPayList(null, null, "createTm", "desc", customerPayQO);
        List<CustomerPayVO> customerPayList = customerPayVODhPageInfo.getList();
        if(customerPayList== null || customerPayList.size()<=0){
            return false;
        }
        List<CustomerPayExport> exportList =  new ArrayList<>();
        for(CustomerPayVO payVo : customerPayList){
            CustomerPayExport payExport = new CustomerPayExport();
            //充值状态转中文
            if(payVo.getPayStatus()!=null){
                if(payVo.getPayStatus()==1){
                    payExport.setPayStatusName("已到账");
                }else if(payVo.getPayStatus()==0){
                    payExport.setPayStatusName("充值中");
                }
            }
            //充值类型转中文 1普通充值 2转入额'
            if(payVo.getPayType()!=null){
                if(payVo.getPayType()==1){
                    payExport.setPayTypeName("普通充值");
                }else if(payVo.getPayType()==2){
                    payExport.setPayTypeName("转入额");
                }
            }
            //到款日期转字符串类型以导出
            if(payVo.getPaymentDate() != null){
                payExport.setPaymentDate(DateUtil.formatDate(payVo.getPaymentDate(),"yyyy-MM-dd"));
            }
            BeanUtils.copyProperties(payVo,payExport);
            exportList.add(payExport);
        }
        Map map = new HashMap<>();
        map.put("客户充值",exportList);
        EasyExcelUtil.writeExcel(map,outputStream);
        return true;
    }

    /**
     * 添加客户充值信息
     * @param customerPay
     */
    @Override
    public void saveCustomerPay(CustomerPay customerPay) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        customerPay.setChsCustomerPayId(CommonUtils.getGUID());
        customerPay.setPayNumber("F"+System.currentTimeMillis());//充值码
        customerPay.setCreatePeopleId(userAccount.getAccountId());
        customerPay.setCreateTm(new Date());
        Integer num = customerPayDbService.saveCustomerPay(customerPay);
        if (num > 0){
            Customer customer = customerDbService.selectCustomerById(customerPay.getCustomerId());
            if (Objects.nonNull(customer)){
                if (customerPay.getPayType() == 1){ //普通充值
                    /*if (Objects.nonNull(customer.getCustomerWallet())){
                        customer.setCustomerWallet(customer.getCustomerWallet().add(customerPay.getPayMoney()));
                    }else {
                        customer.setCustomerWallet(customerPay.getPayMoney());
                    }*/
                }else if (customerPay.getPayType() == 2){ //转入额
                    if (Objects.nonNull(customer.getCustomerShiftWallet())){
                        customer.setCustomerShiftWallet(customer.getCustomerShiftWallet().add(customerPay.getPayMoney()));
                    }else {
                        customer.setCustomerShiftWallet(customerPay.getPayMoney());
                    }
                }

                customerDbService.updateCustomerByPrimaryKey(customer);
            }
        }
    }

    /**
     * 修改充值信息
     * @param customerPay
     */
    @Override
    public boolean updateCustomerPay(CustomerPay customerPay) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        CustomerPay cpay = customerPayDbService.selectCustomerPayById(customerPay.getChsCustomerPayId());
        if (Objects.nonNull(cpay) && 1 == cpay.getPayStatus()){
            return true;
        }
        BigDecimal payMoney =new BigDecimal("0");
        if (Objects.nonNull(cpay)){
            payMoney = cpay.getPayMoney();
        }
        cpay.setPayMoney(customerPay.getPayMoney());
        cpay.setCustomerId(customerPay.getCustomerId());
        cpay.setUpdatePeopleId(userAccount.getAccountId());
        cpay.setUpdateTm(new Date());
        Integer num = customerPayDbService.updateCustomerPay(cpay);
        if (num  > 0){
            Customer customer = customerDbService.selectCustomerById(customerPay.getCustomerId());
            if (Objects.nonNull(customer)){
                if (customerPay.getPayType() == 1){ //普通充值
                    if (Objects.isNull(customer.getCustomerWallet())){
                        customer.setCustomerWallet(payMoney);
                    }
                    BigDecimal newPayMoney =customer.getCustomerWallet().add(customerPay.getPayMoney());
                    newPayMoney = newPayMoney.subtract(payMoney);
                    customer.setCustomerWallet(newPayMoney);
                }else if (customerPay.getPayType() == 2){ //转入额
                    if (Objects.isNull(customer.getCustomerShiftWallet())){
                        customer.setCustomerShiftWallet(payMoney);
                    }
                    BigDecimal newPayMoney =customer.getCustomerShiftWallet().add(customerPay.getPayMoney());
                    newPayMoney = newPayMoney.subtract(payMoney);
                    customer.setCustomerShiftWallet(newPayMoney);
                }
                customerDbService.updateCustomerByPrimaryKey(customer);
            }
        }
        return false;
    }

    /**
     * 删除充值申请
     * @param customerPayId
     * @return
     */
    @Override
    public boolean deleteCustomerPay(String customerPayId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        CustomerPay cpay = customerPayDbService.selectCustomerPayById(customerPayId);
        if (Objects.nonNull(cpay) && 1 == cpay.getPayStatus()){
            return true;
        }
        cpay.setDeleteStatus(1);
        cpay.setUpdateTm(new Date());
        cpay.setUpdatePeopleId(userAccount.getAccountId());
        Integer num = customerPayDbService.updateCustomerPay(cpay);
        return false;
    }

    @Override
    public CustomerPayDetailVO queryCustomerPayDetail(String customerPayId) {
        if(StringUtils.isBlank(customerPayId)){
           return null;
        }


        return customerPayDbService.queryCustomerPayDetail(customerPayId);
    }

    /**
     * 财务确认收款
     * @param
     */
    @Override
    public void notarizeCustomerPay(CustomerPay customerPay) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        customerPay.setUpdatePeopleId(userAccount.getAccountId());
        customerPay.setUpdateTm(new Date());
        customerPay.setPayStatus(1);
        customerPay.setFinanceAccountId(userAccount.getAccountId());
        boolean b = customerPayDbService.notarizeCustomerPay(customerPay);
        if (b){
            Customer customer = customerDbService.selectCustomerById(customerPay.getCustomerId());
            if (Objects.nonNull(customer)){
                if (customerPay.getPayType() == 1) { //普通充值
                    if (Objects.nonNull(customer.getCustomerWallet())) {
                        customer.setCustomerWallet(customer.getCustomerWallet().add(customerPay.getPayMoney()));
                    } else {
                        customer.setCustomerWallet(customerPay.getPayMoney());
                    }
                }
            }
            customerDbService.updateCustomerByPrimaryKey(customer);
        }
    }

    /**
     * 日期类型(全部/本周/本月/本年度)
     * @Author chaifuyou
     * @Date  2021/4/1 16:12
     * @param dateType -(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年；thisToday:今天)
     * @return {@link {java.lang.Integer}}
     */
    private Integer getDateUnit(String dateType) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
            if ("thisToday".equals(dateType)) {
                //今天
                dateUnit = 4;
            }
        }
        return dateUnit;
    }
}
